package www.wen.com.common.lib.extension

import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2

/**
 * @author WEN
 * @Description: Banner 的扩展类
 * @date 2021/7/1 19:26
 */


inline fun ViewPager2.onPageScrolled(
        crossinline action: (
                position: Int, positionOffset: Float, positionOffsetPixels: Int,
        ) -> Unit,
) = addOnPageChangeListener(onPageScrolled = action)


inline fun ViewPager2.onPageSelected(
        crossinline action: (
                position: Int,
        ) -> Unit,
) = addOnPageChangeListener(onPageSelected = action)


inline fun ViewPager2.onPageScrollStateChanged(
        crossinline action: (state: Int) -> Unit,
) = addOnPageChangeListener(onPageScrollStateChanged = action)


inline fun ViewPager2.addOnPageChangeListener(
        crossinline onPageScrolled: (
                position: Int, positionOffset: Float, positionOffsetPixels: Int,
        ) -> Unit = { _, _, _ -> },
        crossinline onPageSelected: (
                position: Int,
        ) -> Unit = { _ -> },
        crossinline onPageScrollStateChanged: (state: Int) -> Unit = {},
): ViewPager2.OnPageChangeCallback {

    val onPageChangeCallback = object : ViewPager2.OnPageChangeCallback() {

        override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
            onPageScrolled.invoke(position, positionOffset, positionOffsetPixels)
        }

        override fun onPageSelected(position: Int) {
            onPageSelected.invoke(position)
        }

        override fun onPageScrollStateChanged(state: Int) {
            onPageScrollStateChanged.invoke(state)
        }
    }
    registerOnPageChangeCallback(onPageChangeCallback)
    return onPageChangeCallback
}

fun <BA : FragmentStateAdapter> ViewPager2.configuration(
        pageLimit: Int,
        enabledSlide: Boolean = true,
        provideAdapter: () -> BA,
        action: Runnable? = null,
        delayMillis: Long = 300,
        onPageSelectedBA: ((position: Int) -> Unit)? = null,
) {
    isUserInputEnabled = enabledSlide
    offscreenPageLimit = pageLimit
    adapter = provideAdapter.invoke()
    onPageSelectedBA?.run { onPageSelected(this) }
    action?.also { postDelayed(it, delayMillis) }
}

